import { Middleware } from '@midwayjs/decorator';
import { NextFunction, Context } from '@midwayjs/koa';
import { Config, IMiddleware, Inject } from '@midwayjs/core';
import { TaskAppService } from '../service/app';
import { RESCODE } from '@cool-midway/core';
import * as _ from 'lodash';

/**
 * 应用校验中间件
 */
@Middleware()
export class TaskAppMiddleware implements IMiddleware<Context, NextFunction> {
  @Inject()
  taskAppService: TaskAppService;

  @Config('koa.globalPrefix')
  prefix;

  resolve() {
    return async (ctx, next: NextFunction) => {
      let { url } = ctx;
      url = url.replace(this.prefix, '');
      const appUrl = '/app/';
      // 路由地址为 app前缀的 需要权限校验
      if (_.startsWith(url, appUrl)) {
        const appId = ctx.get('appId');
        const appSecret = ctx.get('appSecret');
        const appInfo = await this.taskAppService.check(appId, appSecret);
        if (!appInfo) {
          ctx.status = 401;
          ctx.body = {
            code: RESCODE.COMMFAIL,
            message: '应用被禁用或appId、appSecret错误',
          };
          return;
        } else {
          ctx.appInfo = appInfo;
        }
      }
      await next();
    };
  }
}
